package cn.hx.mallorder.controller;

import cn.hx.mallorder.dao.OmsCartItemDao;
import cn.hx.mallorder.dao.OmsOrderDao;
import cn.hx.mallorder.dao.OmsOrderItemDao;
import cn.hx.mallorder.dao.UmsMemberReceiveAddressDao;
import cn.hx.mallorder.entity.OmsCartItem;
import cn.hx.mallorder.entity.OmsOrder;
import cn.hx.mallorder.entity.OmsOrderItem;
import cn.hx.mallorder.entity.UmsMemberReceiveAddress;
import cn.hx.mallorder.util.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.jsonwebtoken.Claims;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class CheckoutController {

    @Resource
    private OmsOrderDao orderDao;

    @Resource
    private OmsOrderItemDao omsOrderItemDao;

    @Resource
    private OmsCartItemDao omsCartItemDao;

    @Resource
    private UmsMemberReceiveAddressDao umsMemberReceiveAddressDao;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    //存入订单order
    public void addOrder(Long ids,HttpServletRequest request) {
        OmsOrder omsOrder = new OmsOrder();
        //得到omsCartItem对象
        OmsCartItem omsCartItem = omsCartItemDao.findById(ids);
        //根据MemberId查询得到一个umsMemberReceiveAddress对象
        //根据查询到的umsMemberReceiveAddress对象生成omsOrder

        UmsMemberReceiveAddress umsMemberReceiveAddress = umsMemberReceiveAddressDao.queryByMemberId(omsCartItem.getMemberId());

        omsOrder.setOrderSn(System.currentTimeMillis() + "");
        omsOrder.setMemberId(umsMemberReceiveAddress.getMemberId());
        omsOrder.setReceiverName(umsMemberReceiveAddress.getName());
        omsOrder.setReceiverDetailAddress(umsMemberReceiveAddress.getDetailAddress());
        omsOrder.setReceiverPhone(umsMemberReceiveAddress.getPhoneNumber());
        omsOrder.setReceiverCity(umsMemberReceiveAddress.getCity());
        omsOrder.setReceiverProvince(umsMemberReceiveAddress.getProvince());
        omsOrder.setReceiverRegion(umsMemberReceiveAddress.getRegion());
        omsOrder.setReceiverPostCode(umsMemberReceiveAddress.getPostCode());
        omsOrder.setStatus(0);
        orderDao.insert(omsOrder);
        List<OmsOrderItem> omsOrderItems = new ArrayList<>();
        omsOrderItems.add(addOrderItem(ids));
        omsOrder.setOmsOrderItems(omsOrderItems);
        Long orderId = orderDao.findLastOrderIdByMemBerId(omsCartItem.getMemberId());


        Cookie[] cookies = request.getCookies();
        Long id = 0L;
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    String value = cookie.getValue();
                    if (JwtUtils.verifyToken(value)) {
                        Claims claims = JwtUtils.getClaims(value);
                        id = Long.valueOf(claims.get("data", Map.class).get("id").toString());
                    }
                }
            }
        }
        //把生成的omsOrder对象存库

        redisTemplate.opsForValue().set("order_" + id + "_" + orderId + "", omsOrder);
        redisTemplate.expire("order_" + omsOrder.getMemberId() + "_" + orderId + "",60*30, TimeUnit.SECONDS);
    }


    //存orderItem
    public OmsOrderItem addOrderItem(Long ids) {
        OmsOrderItem omsOrderItem = new OmsOrderItem();

        //得到omsCartItem和order对象
        OmsCartItem omsCartItem = omsCartItemDao.findById(ids);
        Long orderId = orderDao.findLastOrderIdByMemBerId(omsCartItem.getMemberId());
        //存放order_id
        omsOrderItem.setOrderId(orderId);
        //存放剩余数据
        omsOrderItem.setProductPic(omsCartItem.getProductPic());
        omsOrderItem.setProductPrice(omsCartItem.getPrice());
        omsOrderItem.setProductName(omsCartItem.getProductName());
        omsOrderItemDao.insertOrderItem(omsOrderItem);
        return omsOrderItem;


    }


    @GetMapping("/checkoutes/{id}")
    public String checkoutes(@PathVariable("id") Long id,Model model){

        List<OmsOrderItem> omsOrderItemList = omsOrderItemDao.findItemByOrderId(id);
        Double count = 0.0;
        for (OmsOrderItem omsOrderItem : omsOrderItemList) {
            count+=omsOrderItem.getProductPrice();
        }

        System.out.println(omsOrderItemList);

        model.addAttribute("omsCartItemList",omsOrderItemList);
        model.addAttribute("orderList", orderDao.findAllByOrderId(id));
        model.addAttribute("count", count);


        return "checkout";
    }

    @GetMapping("/checkout/{ids}")
    public String checkout(@PathVariable("ids") String ids, Model model, HttpServletRequest request) {
        List<OmsCartItem> omsCartItemList = new ArrayList<>();
        Double count = 0.0;


        String[] split = ids.split(",");
        for (String id : split) {
            omsCartItemList.add(omsCartItemDao.selectOne(new QueryWrapper<OmsCartItem>().eq("product_id", Long.valueOf(id))));
            addOrderItem(Long.valueOf(id));
            addOrder(Long.valueOf(id),request);

        }


        Long userId=0L;
        Cookie[] cookies = request.getCookies();
        if (cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())){
                    String value = cookie.getValue();
                    if (JwtUtils.verifyToken(value)){
                        Claims claims = JwtUtils.getClaims(value);
                        userId =  Long.valueOf(claims.get("data", Map.class).get("id").toString());
                    }
                }
            }
        }
        Long orderId = orderDao.findLastOrderIdByMemBerId(userId);

        for (OmsCartItem cartItem : omsCartItemList) {
            count += cartItem.getPrice();
        }

        model.addAttribute("omsCartItemList", omsCartItemList);
        model.addAttribute("orderList", orderDao.findAllByOrderId(orderId));
        model.addAttribute("count", count);
        return "checkout";
    }


    @GetMapping("/checkout/paySuccess")
    public String paySuccess(HttpServletRequest request) {
        Long userId=0L;
        Cookie[] cookies = request.getCookies();
        if (cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())){
                    String value = cookie.getValue();
                    if (JwtUtils.verifyToken(value)){
                        Claims claims = JwtUtils.getClaims(value);
                        userId =  Long.valueOf(claims.get("data", Map.class).get("id").toString());
                    }
                }
            }
        }
        Long orderId = orderDao.findLastOrderIdByMemBerId(userId);
        OmsOrder omsOrder1 = new OmsOrder();
        omsOrder1.setId(orderId);
        omsOrder1.setStatus(1);
        orderDao.updateStatus(omsOrder1);
        return "paySuccess";
    }

    @GetMapping("/obligationUpdateStatus")
    public String obligation() {
        return "obligation";
    }


}
